package cn.harry.modular.system.service.impl;

import cn.harry.common.constant.CommonConstant;
import cn.harry.common.model.Option;
import cn.harry.component.security.utils.SecurityUtils;
import cn.harry.modular.system.domain.SysRole;
import cn.harry.modular.system.domain.SysRoleMenu;
import cn.harry.modular.system.mapper.SysRoleMapper;
import cn.harry.modular.system.service.SysRoleMenuService;
import cn.harry.modular.system.service.SysRoleService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private final SysRoleMenuService sysRoleMenuService;

    @Override
    public List<Long> getRoleMenuIds(Long roleId) {
        return sysRoleMenuService.listMenuIdsByRoleId(roleId);
    }

    @Override
    public boolean assignMenusToRole(Long roleId, List<Long> menuIds) {
        SysRole role = this.getById(roleId);
        Assert.isTrue(role != null, "角色不存在");

        // 删除角色菜单
        sysRoleMenuService.remove(
                new LambdaQueryWrapper<SysRoleMenu>()
                        .eq(SysRoleMenu::getRoleId, roleId)
        );
        // 新增角色菜单
        if (CollectionUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> roleMenus = menuIds
                    .stream()
                    .map(menuId -> new SysRoleMenu(roleId, menuId))
                    .toList();
            sysRoleMenuService.saveBatch(roleMenus);
        }

        // 刷新角色的权限缓存
        sysRoleMenuService.refreshRolePermsCache(role.getRoleKey());

        return true;
    }

    @Override
    public List<Option<Long>> listRoleOptions() {
        // 查询数据
        List<SysRole> roleList = this.list(Wrappers.<SysRole>lambdaQuery()
                .ne(!SecurityUtils.isRoot(), SysRole::getRoleKey, CommonConstant.SUPER_ADMIN_ROOT)
                .select(SysRole::getId, SysRole::getName)
                .orderByAsc(SysRole::getSort)
        );

        return of(roleList);
    }

    private List<Option<Long>> of(List<SysRole> roleList) {
        return roleList.stream()
                .map(role -> new Option<>(role.getId(), role.getName()))
                .toList();
    }

}




